import React from 'react';

import { Dispatch, State } from './types';
import { toolTipOpen, modalClose, modalOpen } from '../../util/global';
import navigator from '../../util/navigator';
import { DEBUG, isIOS, PayMethod } from '../../constant';
import PayResult from './constant';
import tracker from '../../util/actionTracker';
import promise from '../../util/promise';
import { systemUtil, aliPay } from '../../util/native';
import { CourseApi, UserApi } from '../../api';
import { Data } from '../../api/course/getCommodityDetail';
import { CommodityBuyInfo } from '../../api/course/paramsInterface';
import { OrderResultStatus } from '../OrderResult/constant';
import { OrderProductInfo } from '../OrderResult/types';
import { pointToYuan } from '../../util/transformMoney';

let dispatch: Dispatch;
let state: State;

let reload = (): void => {};

export default (d: Dispatch, s: State): void => {
  dispatch = d;
  state = s;
};

export const getReload = (): void => {
  reload();
};

export const setCourseCommodity = (value: any): void => {
  dispatch({ type: 'SET_COURSE_COMMODITY', value });
};

export const setSelectedCouponList = (value: any[]): void => {
  dispatch({ type: 'SET_SELECTED_COUPON_LIST', value });
};

export const fetchFailed = (): void => {
  dispatch({ type: 'FETCH_FAILED' });
};

export const setPayMethod = (value: number): void => {
  const { payMethod, courseCommodityInfo } = state;
  const { productId } = courseCommodityInfo;
  dispatch({ type: 'SET_PAY_METHOD', value });
};

export const setOrderId = (value: string): void => {
  dispatch({ type: 'SET_ORDER_ID', value });
};

export const setAgreementSelected = (value: boolean): void => {
  dispatch({ type: 'SET_AGREEMENT_SELECTED', value });
};

export const setYutouCoinNum = (value: number): void => {
  dispatch({ type: 'SET_YUTOU_COIN_NUM', value });
};

export const setSpuList = (value: Data[]): void => {
  dispatch({ type: 'SET_SPU_LIST', value });
};

export const getYutouCoinNum = async (): Promise<void> => {
  const res = await UserApi.getSelfCenter();
  if (res.code === 0) {
    const { yutouCoinNum } = res.data;
    setYutouCoinNum(pointToYuan(yutouCoinNum));
  }
};

export const getCommodity = (productId: number, skuIds: number[]): void => {
  reload = (): void => getCommodity(productId, skuIds);

  // SpuApi.getOrderCoupons({ productId, skuIds })
  //   .then((res): void => {
  //     if (res.code === 0) {
  //       setCourseCommodity({ ...res.data, productId, skuIds });
  //     }
  //   })
  //   .catch((): void => {
  //     fetchFailed();
  //   });
};

interface GoPayResult {
  status: string;
}

export const goPayResult = ({ status }: GoPayResult): void => {
  // setTimeout((): void => {
  //   const { orderId, courseCommodityInfo } = state;
  //   const { productId, skuIds } = courseCommodityInfo;
  //   navigator.replace('PayResult', {
  //     productInfo: {
  //       productId,
  //       productName: showProductName,
  //       skuIds
  //     },
  //     orderId,
  //     status,
  //     payAmount: payAmountValue
  //   });
  // });
};

export const yutouCoinPay = (): void => {
  // const { courseCommodityInfo } = state;
  // const {} = courseCommodityInfo;
  // const hasAlipay = systemUtil.checkAliPayInstalled();
  // if (userPay > coinAmount) {
  //   navigator.push('Charge');
  //   return;
  // }
  // 购买课程
  // OrderApi.createOrder({}).then((res): void => {
  //   if (res.code === 0) {
  //     const { orderId } = res.data;
  //     setOrderId(orderId);
  //     checkPayResult();
  //   }
  // });
};

export const back = (): void => {
  navigator.goBack();
};

export const checkPayResult = async (orderId: string): Promise<void> => {
  const res = await CourseApi.checkBuyCommodityResult({ orderId });
  const { code, data } = res;
  if (code !== 0) return;

  const { orderStatus, payAmount, payTimestamp } = data;

  if (
    orderStatus !== OrderResultStatus.PayFail &&
    orderStatus !== OrderResultStatus.PaySuccess
  ) {
    return;
  }

  const { spuList } = state;
  navigator.replace('OrderResult', {
    orderInfo: {
      status: orderStatus,
      orderId,
      productList: spuList.map(
        (item): OrderProductInfo => ({
          id: item.commodityId,
          name: item.commodityName
        })
      ),
      payAmount,
      payTime: payTimestamp
    }
  });
};

export const pay = async (totalPrice: number): Promise<void> => {
  const { spuList } = state;

  const param = {
    buyCommodities: spuList.map(
      (item): CommodityBuyInfo => ({
        commodityId: item.commodityId,
        commodityPriceForSale: item.realPrice
      })
    ),
    payAmount: totalPrice,
    payMethod: PayMethod.YuTouCoin
  };

  const res = await CourseApi.buyCommodity(param);
  const { code, data } = res;
  if (code !== 0) return;
  const { orderId } = data;

  checkPayResult(orderId);
};
